import { Message } from 'element-ui';
import auth from '@/service/auth';

function errorHandler(data) {
  const { msg } = data;

  Message.error({
    message: msg || 'Request error, Please try again later', // 请求出错, 请稍后重试
    duration: 3000
  });
  // if (msg === 'Network Error') {
  //   auth.expireToLogin();
  // }
}

export default (instance) => {
  // Add a response interceptor
  instance.interceptors.response.use((response) => {
    const data = JSON.parse(response.data);
    if (data.status === '0') {
      if (data.error === '70000104') {
        console.warn('dsads')
        auth.expireToLogin();
        return;
      }
      if (response.config.showDefaultError !== false) {
        errorHandler(data);
      }
    } else if (data.status === '1' && (data.error === '70000104' || data.error === '70000103')) {
      auth.expireToLogin();
      return;
    }

    return response;
  }, (error) => {
    // Do something with response error
    const data = {
      error,
      msg: ''
    };

    if (error.response) {
      data.msg = error.response.data && error.response.data.msg;
    } else {
      data.msg = error.message;
    }

    errorHandler(data);

    return Promise.reject(error);
  });
};
